package com.example.shop.es.config;

import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.apache.http.message.BasicHeader;
import org.apache.http.nio.conn.ssl.SSLIOSessionStrategy;
import org.apache.http.ssl.SSLContexts;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.elasticsearch.ElasticsearchRestClientProperties;
import org.springframework.boot.autoconfigure.elasticsearch.RestClientBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.KeyStore;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.apache.http.nio.conn.ssl.SSLIOSessionStrategy;
import org.apache.http.ssl.SSLContextBuilder;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.convert.ElasticsearchConverter;

import javax.annotation.PostConstruct;
import javax.net.ssl.SSLContext;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.time.Duration;

@Configuration
public class EsConfig {

    @Bean("esTemplate")
    public ElasticsearchRestTemplate elasticsearchRestTemplate(RestHighLevelClient elasticsearchClient, ElasticsearchConverter elasticsearchConverter){
        return new ElasticsearchRestTemplate(elasticsearchClient,elasticsearchConverter);
    }








//    @Autowired
//    ElasticsearchRestClientProperties properties;
//
//    @Bean("esClient")
//    RestHighLevelClient elasticsearchRestHighLevelClient() {
//        try{
//            String userName = properties.getUsername();
//            String password = properties.getPassword();
//            String auth = Base64.encodeBase64String((userName + ":" + password).getBytes());
//            final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
//            credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, password));
//
////            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(, new TrustStrategy() {
////                // 信任所有
////                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
////                    return true;
////                }
////            }).build();
////            SSLContext sslContext = SSLContextBuilder.create().loadTrustMaterial((x, y) -> true).build();
//
//            Path trustStorePath = Paths.get(ESConfig.class.getResource("certificates/elastic-certificates.p12").toURI());
//            KeyStore truststore = KeyStore.getInstance("pkcs12");
//
//            InputStream is = Files.newInputStream(trustStorePath);
//            truststore.load(is, "".toCharArray());
//            SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(truststore, null).build();
//            SSLIOSessionStrategy sessionStrategy = new SSLIOSessionStrategy(sslContext, NoopHostnameVerifier.INSTANCE);
//            credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, password));
//            HttpHost[] hosts = new HttpHost[]{
//                    new HttpHost("127.0.0.1",9300,"https"),
//                    new HttpHost("127.0.0.1",9301,"https"),
//                    new HttpHost("127.0.0.1",9302,"https"),
//            };
//
//            RestClientBuilder builder = RestClient.builder(hosts);
//            //设置http连接
//            builder.setHttpClientConfigCallback((HttpAsyncClientBuilder httpAsyncClientBuilder) ->{
//                httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
//                httpAsyncClientBuilder.disableAuthCaching();
//
//                httpAsyncClientBuilder.setSSLStrategy(sessionStrategy);
//                return httpAsyncClientBuilder;
//            });
//            return new RestHighLevelClient(builder);
//        }catch (Exception e){
//            e.printStackTrace();
//        }
//        return null;
//    }

//    @Bean
//    RestClientBuilder elasticsearchRestClientBuilder(ObjectProvider<RestClientBuilderCustomizer> builderCustomizers){
//        HttpHost[] hosts = new HttpHost[]{
//          new HttpHost("127.0.0.1",9300,"http"),
//          new HttpHost("127.0.0.1",9301,"http"),
//          new HttpHost("127.0.0.1",9302,"http"),
//        };
//        RestClientBuilder builder = RestClient.builder(hosts);
//        builder.setHttpClientConfigCallback((httpClientBuilder) -> {
//            builderCustomizers.orderedStream().forEach((customizer) -> customizer.customize(httpClientBuilder));
//            return httpClientBuilder;
//        });
//        builder.setRequestConfigCallback((requestConfigBuilder) -> {
//            builderCustomizers.orderedStream().forEach((customizer) -> customizer.customize(requestConfigBuilder));
//            return requestConfigBuilder;
//        });
//        builderCustomizers.orderedStream().forEach((customizer) -> customizer.customize(builder));
//        return builder;
//    }



}
